package com.ruoyi.StarStudio.Controller;

import com.github.pagehelper.PageInfo;
import com.ruoyi.StarStudio.Entity.*;
import com.ruoyi.StarStudio.RabbitMQ.MQSender;
import com.ruoyi.StarStudio.Service.PanicBuyingCouponsService;
import com.ruoyi.StarStudio.Service.PanicBuyingGoodsService;
import com.ruoyi.StarStudio.Service.PanicBuyingOrdersService;
import com.ruoyi.StarStudio.Utils.JsonUtil;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.PageUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/pb_orders")
public class PanicBuyingOrdersController implements InitializingBean {

    @Autowired
    PanicBuyingOrdersService panicBuyingOrdersService;

    @Autowired
    PanicBuyingGoodsService panicBuyingGoodsService;

    @Autowired
    PanicBuyingCouponsService panicBuyingCouponsService;

    @Autowired
    RedisCache redisCache;

    @Autowired
    MQSender mqSender;

    private final Map<Long,Boolean> EmptyGoodsStockMap = new HashMap<>(); //商品库存是否为空的标识
    private final Map<Long,Boolean> EmptyCouponsStockMap = new HashMap<>(); //优惠券库存是否为空的标识

    /**
     * 带搜索条件分页查询
     * @param panicBuyingOrders 抢购订单对象
     * @return 结果对象 Result
     */
    @GetMapping("/page")
    public PageResult findPanicBuyingOrdersList(PanicBuyingOrders panicBuyingOrders){
        PageUtils.startPage();
        List<PanicBuyingOrders> panicBuyingOrdersList;
        long totalRecord;
        try {
            panicBuyingOrdersList = panicBuyingOrdersService.findPanicBuyingOrdersList(panicBuyingOrders);
             totalRecord = panicBuyingOrdersService.findTotalRecord();
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PANIC_BUYING_ORDERS_FAIL);
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PANIC_BUYING_ORDERS_SUCCESS,new PageInfo<>(panicBuyingOrdersList).getTotal(),panicBuyingOrdersList,totalRecord);
    }

    /**
     *  抢购接口
     * @param orders 订单对象
     * @return 结果对象 Result
     */
    @PostMapping
    public Result NewPanicBuyingOrders(@RequestBody Orders orders){
        orders.setNumber(1);//每个用户只能抢一件
        if (orders.getOrder_user_id() == 0){
            return new Result(HttpStatusCode.ERROR,MessageConstant.USER_NO_EXIST);
        }
        if (orders.getGoods_id() > 0 && orders.getCoupons_id() == 0){ /* 实体商品抢购 */
            //判断是否重复抢购
            PanicBuyingOrders panicBuyingOrders = redisCache.getCacheObject("panic_buying_goods_order:" + orders.getOrder_user_id() + ":" + orders.getGoods_id());
            if (panicBuyingOrders != null){
                return new Result(HttpStatusCode.ERROR,MessageConstant.ONLY_ONE_GOODS_CAN_BUY_PER_PERSON);
            }
            //通过内存标记减少 Redis访问
            if (EmptyGoodsStockMap.get(orders.getGoods_id())){
                return new Result(HttpStatusCode.ERROR,MessageConstant.OUT_OF_GOODS_STOCK);
            }
            //Redis预减库存
            Integer stock = redisCache.getCacheObject("panic_buying_goods:" + orders.getGoods_id());
            if (stock < 1){
                EmptyGoodsStockMap.put(orders.getGoods_id(),true);
                return new Result(HttpStatusCode.ERROR,MessageConstant.OUT_OF_GOODS_STOCK);
            }
            redisCache.setCacheObject("panic_buying_goods:" + orders.getGoods_id(), stock - 1);
            //向rabbitmq broker发送数据
            //因为使用了rabbitmq，使得抢购变成异步操作，达到流量削峰的效果  同时可以快速返回信息(如："正在努力抢购中...")给用户  体验较好
            mqSender.sendPanicBuyingMessage(JsonUtil.object2JsonStr(orders));
            return new Result(HttpStatusCode.SUCCESS,MessageConstant.PANIC_BUYING);
        } else if (orders.getOrder_id() == 0 && orders.getCoupons_id() > 0) { //优惠券抢购
            PanicBuyingOrders panicBuyingOrders = redisCache.getCacheObject("panic_buying_coupons_order:" + orders.getOrder_user_id() + ":" + orders.getCoupons_id());
            if (panicBuyingOrders != null){
                return new Result(HttpStatusCode.ERROR,MessageConstant.ONLY_ONE_GOODS_CAN_BUY_PER_PERSON);
            }
            //通过内存标记减少 Redis访问
            if (EmptyCouponsStockMap.get(orders.getCoupons_id())){
                return new Result(HttpStatusCode.ERROR,MessageConstant.OUT_OF_GOODS_STOCK);
            }
            //Redis预减库存
            Integer stock = redisCache.getCacheObject("panic_buying_coupons:" + orders.getCoupons_id());
            if (stock < 1){
                EmptyCouponsStockMap.put(orders.getCoupons_id(),true);
                return new Result(HttpStatusCode.ERROR,MessageConstant.OUT_OF_COUPONS_STOCK);
            }
            redisCache.setCacheObject("panic_buying_coupons:" + orders.getCoupons_id(), stock - 1);
            //向rabbitmq broker发送数据
            //因为使用了rabbitmq，使得秒杀变成异步操作，达到流量削峰的效果  同时可以快速返回信息(如："正在努力抢购中...")给用户  体验较好
            mqSender.sendPanicBuyingMessage(JsonUtil.object2JsonStr(orders));
            return new Result(HttpStatusCode.SUCCESS,MessageConstant.PANIC_BUYING);
        }
        return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.INCORRECT_CLIENT_REQUEST);
    }


    /**
     * 系统初始化时将抢购商品库存加载到 Redis
     */
    @Override
    public void afterPropertiesSet() {
        List<PanicBuyingGoods> panicBuyingGoodsList = panicBuyingGoodsService.PanicBuyingGoodsList();
        if (CollectionUtils.isEmpty(panicBuyingGoodsList)){
            return;
        }
        panicBuyingGoodsList.forEach(panicBuyingGoods -> {
            redisCache.setCacheObject("panic_buying_goods:" + panicBuyingGoods.getGoods_id(),panicBuyingGoods.getPanic_buying_goods_stock());
            EmptyGoodsStockMap.put(panicBuyingGoods.getGoods_id(),false);
        });

        List<PanicBuyingCoupons> panicBuyingCouponsList = panicBuyingCouponsService.PanicBuyingCouponsList();
        if (CollectionUtils.isEmpty(panicBuyingCouponsList)){
            return;
        }
        panicBuyingCouponsList.forEach(panicBuyingCoupons -> {
            redisCache.setCacheObject("panic_buying_coupons:" + panicBuyingCoupons.getCoupons_id(), panicBuyingCoupons.getPanic_buying_coupons_stock());
            EmptyCouponsStockMap.put(panicBuyingCoupons.getCoupons_id(),false);
        });
    }

    /**
     * 定时任务 每分钟检查 Redis中的商品库存数量和优惠券库存数量
     */
    @Scheduled(cron ="0 */1 * * * ?")
    public void AutoCheckRedisStockStatus(){
        List<PanicBuyingGoods> panicBuyingGoodsList = panicBuyingGoodsService.PanicBuyingGoodsList();
        if (CollectionUtils.isEmpty(panicBuyingGoodsList)){
            return;
        }
        for (PanicBuyingGoods panicBuyingGoods : panicBuyingGoodsList) {
            Integer goodsStock = redisCache.getCacheObject("panic_buying_goods:" + panicBuyingGoods.getGoods_id());
            if (goodsStock > 0){
                EmptyGoodsStockMap.put(panicBuyingGoods.getGoods_id(),false);
            }
        }
        List<PanicBuyingCoupons> panicBuyingCouponsList = panicBuyingCouponsService.PanicBuyingCouponsList();
        if (CollectionUtils.isEmpty(panicBuyingCouponsList)){
            return;
        }
        for (PanicBuyingCoupons panicBuyingCoupons : panicBuyingCouponsList) {
            Integer couponsStock = redisCache.getCacheObject("panic_buying_coupons:" + panicBuyingCoupons.getCoupons_id());
            if (couponsStock > 0){
                EmptyCouponsStockMap.put(panicBuyingCoupons.getCoupons_id(),false);
            }
        }
    }
}
